package com.jiangjun.fetch.filter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jiangjun.fetch.FetchRss;
import com.jiangjun.fetch.common.AttributeChain;
import com.jiangjun.fetch.common.ConstantVariable;
import com.jiangjun.fetch.common.ImageFetch;
import com.jiangjun.fetch.common.WebContext;
import com.jiangjun.fetch.mongo.MongoDBSupport;
import com.jiangjun.fetch.scale.ImageHelper;
import com.jiangjun.fetch.scale.ImageImpl;
import com.jiangjun.fetch.scale.ScaleByIm4java;
import com.jiangjun.fetch.servlet.Start;
import com.mongodb.DBObject;

public class ScaleImageFilter extends Filter {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public String doProcess(final WebContext ctx) throws Exception {
		// TODO Auto-generated method stub
		// 图片处理
		List<ImageFetch> isList = ctx.getImgList();
		for (ImageFetch is : isList) {
			/**
			 * 1.抓取 2.获取type 3.获取路径
			 */
			HttpParams params = new BasicHttpParams();
			params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,
					false);
			// params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
			// HTTP.UTF_8);
			params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
					HttpVersion.HTTP_1_1);
			params.setParameter(ClientPNames.COOKIE_POLICY,
					CookiePolicy.BROWSER_COMPATIBILITY);
			params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
			params.setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
			params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,
					true);
			params.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
			params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
					10000);
			params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(is.getImg_src());
			httpGet.setParams(params);
			// 部分网站图片请求返回403
			httpGet.setHeader("Referer", ctx.getUrl());
			httpGet.setHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0");
			try {
				HttpResponse response = httpClient.execute(httpGet);
				System.out.println(response.getStatusLine().getStatusCode());
				if (response.getStatusLine().getStatusCode() == 200) {
					ImageImpl imageImpl = new ImageImpl();
					HttpEntity entity = response.getEntity();
					Header contentType = entity.getContentType();
					// 从content-type判断图片的格式
					String type = imageImpl
							.getImageTypeByContentType(contentType.getValue());
					byte[] result = EntityUtils.toByteArray(entity);
					if ("".equals(type)) {
						// 从byte[]中获取图片格式
						type = imageImpl.getImageTypeByByteArray(result);
						if ("".equals(type)) {
							type = imageImpl.getImageType(is.getImg_src());
							if ("".equals(type)) {
								type = "jpg";
							}
						}
					}

					if (type.equalsIgnoreCase("jpeg"))
						type = "jpg";

					String sourcePath = imageImpl.getPath(ctx, type,
							is.getId(), 0, 0);
					imageImpl.saveFile(result, sourcePath);
					is.setImg_path(sourcePath);
					is.setType(type);
					if ("".equals(ctx.getImg_db_path())) {
						ctx.setImg_db_path(sourcePath);
					} else {
						ctx.setImg_db_path(ctx.getImg_db_path() + ";"
								+ sourcePath);
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				is = null;
				e.printStackTrace();
			} finally {
				httpClient.getConnectionManager().shutdown();
			}
			if (!doImage(is, ctx)) {
				is.setNeedRemove(true);
			}
		}

		String type = ctx.getType();
		if (type.equals("1") || type.equals("3")) {
			String collectionName = "";
			if (type.equals("1")) {
				collectionName = MongoDBSupport._FETCHPIC;
			} else if (type.equals("3")) {
				collectionName = MongoDBSupport._FETCHPICLIST;
			}
			// 保存
			FetchRss fetch = ctx.getFetch();
			fetch.setImg_path(ctx.getImg_db_path());
			if (ctx.getMin_img_db_path() != null
					&& !"".equals(ctx.getMin_img_db_path())) {
				fetch.setMin_img_path(ctx.getMin_img_db_path());
			}
			DBObject object = fetch.toDbObject();
			MongoDBSupport mongoDBSupport = MongoDBSupport.getInstance();
			mongoDBSupport.save(object, collectionName);
			return null;
		}
		return AttributeChain.SAVE_FILTER;
	}

	private boolean doImage(ImageFetch is, WebContext ctx) throws Exception {
		ScaleByIm4java scaleByIm4java = new ScaleByIm4java();
		ImageHelper imageHelper = new ImageImpl();
		if (is != null) {
			try {
				logger.info("================================"
						+ is.getImg_path());
				BufferedImage bi = ImageIO.read(new File(is.getImg_path()));
				int sourceWidth = bi.getWidth();
				int sourceHeight = bi.getHeight();
				is.setWidth(sourceWidth);
				is.setHeight(sourceHeight);

				ArrayList<String> screen = Start.screen;
				for (String d : screen) {
					String target_path = imageHelper.getPath(ctx, is.getType(),
							is.getId(), 2, Integer.parseInt(d));
					double scale = scaleByIm4java.getScaleByWidth(
							Double.parseDouble(d), sourceWidth);
					if (d.equals("320")) {
						is.setScale_min(scale + "");
					} else {
						is.setScale_max(scale + "");
					}

					scaleByIm4java.scale(scale, is.getImg_path(), target_path);

					/**
					 * 压缩缩略图 （1）先判断原图的尺寸是否小于130和110,小于则不用这张原图为基础来取缩略图
					 * （2）判断原图的高是否是宽的2倍，如果是则continue （3）判断原图的比例是否可以采用宽度来压缩的方法来压缩
					 * （4）按照坐标算法来剪裁(在压缩之后的图片的基础上)
					 */
					if (ctx.getMin_img_db_path() == null
							|| "".equals(ctx.getMin_img_db_path())) {
						if (sourceWidth < ConstantVariable.mini_width
								|| sourceHeight < ConstantVariable.mini_height)
							continue;
						if (((double) sourceHeight / (double) sourceWidth) > ConstantVariable.RATIO)
							continue;
						if (((double) sourceWidth / (double) sourceHeight) > ConstantVariable.RATIO)
							continue;
						// if (wh > 1.0 && wh < 1.3) {
						// 采用以宽度为基础来压缩
						String min_img_db_path = imageHelper.getPath(ctx,
								is.getType(), is.getId(), 1, 0);
						scaleByIm4java.scale(is.getImg_path(), min_img_db_path,
								ConstantVariable.mini_width,
								ConstantVariable.mini_height, 1);
						ctx.setMin_img_db_path(min_img_db_path);
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}
}
